import 'dart:io';

import 'package:fake_handwriting/generated/l10n.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:jwt_decode/jwt_decode.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
class Util {
  static const MethodChannel _channel = MethodChannel('fake_handwriting');
  static toast(String content) async {
    return await _channel.invokeMethod('toast', {"content": content});
  }
  static Future<void> shareFile(String path) async {
    await _channel.invokeMethod('shareFile', {"path": path});
  }
  static getCacheDir() async {
    return await _channel.invokeMethod('getCacheDir');
  }
  static removeToken() async {
    var pref = await SharedPreferences.getInstance();
    await pref.setString("token", "");
  }
  static Future<void> loginSuccess(String token) async {
    var pref = await SharedPreferences.getInstance();
    await pref.setString("token", token);
  }
  static showLoading(context) {
    Size size = MediaQuery.of(context).size;
    showDialog(
        barrierDismissible: false,
        context: context,
        builder: (context) {
          return Material(
            color: Colors.grey.withOpacity(0.1),
            child: Center(
              child: Container(
                  padding: const EdgeInsets.symmetric(vertical: 30),
                  width: size.width / 2,
                  color: Colors.white,
                  child: Row(
                    children: const [
                      CircularProgressIndicator(),
                      Padding(
                          padding: EdgeInsets.only(left: 20),
                          child: Text("Loading..."))
                    ],
                    mainAxisAlignment: MainAxisAlignment.center,
                  )),
            ),
          );
        });
  }
  static Future<ByteData> getByteData(File file) async {
    return ((await file.readAsBytes()).buffer.asByteData());
  }
  static println(String v){
    // print("emmmmmm $v\n");
  }
  static Future<void> showInputNumberDialog(BuildContext context,var defaultValue,Function(bool isCancel,int res) back) async {
    var _controller=TextEditingController();
    _controller.text="$defaultValue";
    int? res=await showDialog(context: context, builder:(c)=>SimpleDialog(
      title:Text(S.of(context).pleaseEnterANumber),
      children: [
        TextField(
          controller: _controller,
          keyboardType: TextInputType.number,
          inputFormatters: [
            FilteringTextInputFormatter.allow(RegExp("[0-9]"))
          ],
          textAlign: TextAlign.center,
          autofocus: true,
          decoration: const InputDecoration(
            border: InputBorder.none,
          ),
        ),
        Row(children: [
          ElevatedButton(onPressed:(){
            Navigator.pop(context,-1);
          }, child: Text(S.of(context).cancel)),
          ElevatedButton(onPressed:(){
            if(_controller.text.isEmpty){
              toast(S.of(context).pleaseEnterANumber);
            }else{
              try{
                Navigator.pop(context,int.parse(_controller.text));
              }catch(e){
                toast(S.of(context).valueIsOutOfRange);
                back(true,-1);
                Navigator.pop(context);
              }
            }
          }, child: Text(S.of(context).confirm)),
        ],mainAxisAlignment: MainAxisAlignment.spaceAround,)
      ],
    ));
    if(res==null||res==-1){
      back(true,-1);
    }else{
      back(false,res);
    }
  }
  static Future<Map<String,dynamic>?>getTokenInfo() async {
    var sp = await SharedPreferences.getInstance();
    var token=sp.getString("token");
    if(token==null||token.isEmpty){
      return null;
    }else{
      return Jwt.parseJwt(token);
    }
  }

  static Future<bool> checkPermission(BuildContext context) async {
    if(!(await Permission.storage.isGranted)){
      bool? isApply=await showCupertinoDialog(context: context, barrierDismissible: true, builder:(c)=>SimpleDialog(
        title: Text(S.of(context).tips),
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 24,vertical: 8),
            child: Text(S.of(context).permissionTips),
          ),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 24,vertical: 8),
            child: Row(children: [
              ElevatedButton(onPressed:(){
                Navigator.pop(context,false);
              },child: Text(S.of(context).cancel)),
              const SizedBox(width: 10,),
              ElevatedButton(onPressed:(){
                Navigator.pop(context,true);
              },child: Text(S.of(context).grant)),
            ],mainAxisAlignment: MainAxisAlignment.end,),
          )
        ],
      ));
      if(isApply!=null&&isApply){
        if(PermissionStatus.granted!=await Permission.storage.request()){
          // print("没有授予");
          return false;
          //又被取消了
        }else{
          return true;
        }
      }else{
        return false;
        //弹窗拒绝了
      }
    }else{
      return true;
    }
  }
}